<?php

class SeoUrlRule extends CBaseUrlRule
{
	public $connectionID = 'db';
	private $rules = array();
	private $escapeSymbols = array( ',', '/','!','#','~','@','%','^','&', '?','/','\\','|','-' );
	
	
	public function __construct()
	{
		$seoModules = getSeoModules();
		foreach ($seoModules as $m)
		{
			Yii::import('application.modules.install.models.*');
			$config = Install::getModuleInstaller($m['name'])->config();
			$this->rules = array_merge($config['dependencies']['seo']['rules'], $this->rules);
		}
	}
	
	private function _parseRoute(&$route, &$params)
	{
		$tempRoute = parse_url($route);
		parse_str($tempRoute['query'], $tempParams);
		
		$params = array_merge($params, $tempParams);
		$route = $tempRoute['path'];
	}
	
	public function createUrl($manager,$route,$params,$ampersand)
    {
		$this->_parseRoute($route, $params);
		
		if (isset($this->rules[$route]))
		{
			$language = $params['language'];
			unset($params['language']);
			$defaultUrl = $manager->removeUrlSuffix($manager->createUrlDefault($route,$params,$ampersand), $manager->urlSuffix);
			
			$alias = SeoRouting::model()->createAlias($this->rules[$route], $params, $manager->urlSuffix, $defaultUrl, $this->escapeSymbols);
			
			if (!empty($language))
				$alias = $alias.'?language='.$language;
			return $alias;
		}
		
        return false;  // this rule does not apply
    }
 
    public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
    {
		$alias = str_replace('%2F','/',urlencode($pathInfo));
		return $manager->removeUrlSuffix(SeoRouting::model()->getUrlByAlias($alias), $manager->urlSuffix);
    }
	
}

?>
